package org.jeecg.modules.solitaire_app.app.controller;

import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.solitaire_app.app.entity.YsyOnsiteApply;
import org.jeecg.modules.solitaire_app.app.entity.YsyRefinery;
import org.jeecg.modules.solitaire_app.app.entity.YsyUsers;
import org.jeecg.modules.solitaire_app.app.service.IYsyOnsiteApplyService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.solitaire_app.app.service.IYsyRefineryService;
import org.jeecg.modules.solitaire_app.app.service.IYsyUsersService;
import org.jeecg.modules.system.entity.SysAnnouncement;
import org.jeecg.modules.system.service.ISysAnnouncementService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 驻场申请
 * @Author: jeecg-boot
 * @Date: 2023-08-30
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "驻场申请")
@RestController
@RequestMapping("/app/ysyOnsiteApply")
public class YsyOnsiteApplyController extends JeecgController<YsyOnsiteApply, IYsyOnsiteApplyService> {
    @Autowired
    private IYsyOnsiteApplyService ysyOnsiteApplyService;
    @Autowired
    private IYsyUsersService ysyUsersService;
    @Autowired
    private IYsyRefineryService refineryService;
    @Autowired
    private ISysAnnouncementService sysAnnouncementService;

    /**
     * 分页列表查询
     *
     * @param ysyOnsiteApply
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "驻场申请-分页列表查询")
    @ApiOperation(value = "驻场申请-分页列表查询", notes = "驻场申请-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(YsyOnsiteApply ysyOnsiteApply,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<YsyOnsiteApply> queryWrapper = QueryGenerator.initQueryWrapper(ysyOnsiteApply, req.getParameterMap());
        Page<YsyOnsiteApply> page = new Page<YsyOnsiteApply>(pageNo, pageSize);
        IPage<YsyOnsiteApply> pageList = ysyOnsiteApplyService.page(page, queryWrapper);
        pageList.getRecords().stream().forEach(item -> {
            String[] ids = item.getRefineryIds().split(",");
            List<YsyRefinery> refineries = refineryService.list(Wrappers.<YsyRefinery>lambdaQuery().in(YsyRefinery::getRefineryId, Arrays.asList(ids)));
            List<String> names = new ArrayList<>();
            refineries.stream().forEach(_item -> {
                names.add(_item.getRefineryName());
            });
            item.setRefineryNames(names.toString());
        });
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param ysyOnsiteApply
     * @return
     */
    @AutoLog(value = "驻场申请-添加")
    @ApiOperation(value = "驻场申请-添加", notes = "驻场申请-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody YsyOnsiteApply ysyOnsiteApply) {
        YsyOnsiteApply onsiteApplyDB = ysyOnsiteApplyService.getOne(Wrappers.<YsyOnsiteApply>lambdaQuery().
                eq(YsyOnsiteApply::getUserId, ysyOnsiteApply.getUserId()).eq(YsyOnsiteApply::getStatus, 0));
        if (ObjectUtil.isNotNull(onsiteApplyDB)) {
            return Result.error("您已提交申请，请等待审核");
        }

        YsyOnsiteApply onsiteApplyDB1 = ysyOnsiteApplyService.getOne(Wrappers.<YsyOnsiteApply>lambdaQuery().
                eq(YsyOnsiteApply::getUserId, ysyOnsiteApply.getUserId()).eq(YsyOnsiteApply::getStatus, 1));
        if (ObjectUtil.isNotNull(onsiteApplyDB1)) {
            return Result.error("审核已通过，无需重复提交");
        }

        YsyOnsiteApply onsiteApplyDB2 = ysyOnsiteApplyService.getOne(Wrappers.<YsyOnsiteApply>lambdaQuery().
                eq(YsyOnsiteApply::getUserId, ysyOnsiteApply.getUserId()).eq(YsyOnsiteApply::getStatus, 2));
        if (ObjectUtil.isNotNull(onsiteApplyDB2)) {
            ysyOnsiteApply.setStatus(0);
            ysyOnsiteApply.setCreateTime(new Date());
            ysyOnsiteApply.setId(onsiteApplyDB2.getId());
            ysyOnsiteApplyService.updateById(ysyOnsiteApply);

            //发公告通知处理
            SysAnnouncement sysAnnouncement = new SysAnnouncement();
            sysAnnouncement.setTitile("入驻申请通知");
            sysAnnouncement.setMsgContent("有新用户入驻申请，请尽快去处理！！！！");
            sysAnnouncement.setCreateTime(new Date());
            sysAnnouncement.setSendTime(new Date());
            sysAnnouncement.setSendStatus("1");
            sysAnnouncement.setMsgType("ALL");
            sysAnnouncement.setPriority("H");
            sysAnnouncement.setDelFlag("0");
            sysAnnouncement.setSender("admin");
            sysAnnouncement.setStartTime(new Date());
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_YEAR, 1);
            sysAnnouncement.setEndTime(calendar.getTime());
            sysAnnouncementService.save(sysAnnouncement);

            return Result.ok("添加成功！");
        }

        //发公告通知处理
        SysAnnouncement sysAnnouncement = new SysAnnouncement();
        sysAnnouncement.setTitile("入驻申请通知");
        sysAnnouncement.setMsgContent("有新用户入驻申请，请尽快去处理！！！！");
        sysAnnouncement.setCreateTime(new Date());
        sysAnnouncement.setSendTime(new Date());
        sysAnnouncement.setSendStatus("1");
        sysAnnouncement.setMsgType("ALL");
        sysAnnouncement.setPriority("H");
        sysAnnouncement.setDelFlag("0");
        sysAnnouncement.setSender("admin");
        sysAnnouncement.setStartTime(new Date());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        sysAnnouncement.setEndTime(calendar.getTime());
        sysAnnouncementService.save(sysAnnouncement);

        ysyOnsiteApplyService.save(ysyOnsiteApply);

        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param ysyOnsiteApply
     * @return
     */
    @AutoLog(value = "驻场申请-编辑")
    @ApiOperation(value = "驻场申请-编辑", notes = "驻场申请-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody YsyOnsiteApply ysyOnsiteApply) {
        if (ObjectUtil.isNotNull(ysyOnsiteApply.getStatus()) && ysyOnsiteApply.getStatus() == 1) {
            YsyUsers ysyUsers = ysyUsersService.getOne(Wrappers.<YsyUsers>lambdaQuery()
                    .eq(YsyUsers::getId, ysyOnsiteApply.getUserId()));
            ysyUsers.setRealFlag(1);
            ysyUsers.setRealName(ysyOnsiteApply.getUserName());
            ysyUsersService.updateById(ysyUsers);
            ysyOnsiteApply.setAuditTime(new Date());
        }
        ysyOnsiteApplyService.updateById(ysyOnsiteApply);
        return Result.ok("编辑成功!");
    }

    /**
     * 编辑
     *
     * @param ysyOnsiteApply
     * @return
     */
    @AutoLog(value = "驻场申请-用户编辑")
    @ApiOperation(value = "驻场申请-编辑", notes = "驻场申请-编辑")
    @PutMapping(value = "/userEdit")
    public Result<?> userEdit(@RequestBody YsyOnsiteApply ysyOnsiteApply) {
        YsyOnsiteApply ysyOnsiteApply1 = ysyOnsiteApplyService.getOne(Wrappers.<YsyOnsiteApply>lambdaQuery()
                .eq(YsyOnsiteApply::getUserId, ysyOnsiteApply.getUserId()));
        ysyOnsiteApply1.setRefineryIds(ysyOnsiteApply.getRefineryIds());
        ysyOnsiteApplyService.updateById(ysyOnsiteApply1);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "驻场申请-通过id删除")
    @ApiOperation(value = "驻场申请-通过id删除", notes = "驻场申请-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        ysyOnsiteApplyService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "驻场申请-批量删除")
    @ApiOperation(value = "驻场申请-批量删除", notes = "驻场申请-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.ysyOnsiteApplyService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "驻场申请-通过id查询")
    @ApiOperation(value = "驻场申请-通过id查询", notes = "驻场申请-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        YsyOnsiteApply ysyOnsiteApply = ysyOnsiteApplyService.getById(id);
        return Result.ok(ysyOnsiteApply);
    }

    /**
     * 通过id查询
     *
     * @param userId
     * @return
     */
    @AutoLog(value = "驻场申请-查询用户入驻状态")
    @ApiOperation(value = "驻场申请-查询用户入驻状态", notes = "驻场申请-查询用户入驻状态")
    @GetMapping(value = "/getUserApplyDetail/{userId}")
    public Result<YsyOnsiteApply> getUserApplyDetail(@PathVariable("userId") String userId) {
        Result<YsyOnsiteApply> result = new Result<>();
        YsyOnsiteApply ysyOnsiteApply = ysyOnsiteApplyService.getOne(Wrappers.<YsyOnsiteApply>lambdaQuery()
                .eq(YsyOnsiteApply::getUserId, userId));

        if (ObjectUtil.isEmpty(ysyOnsiteApply)) {
            result.setCode(200);
            result.setSuccess(true);
            result.setMessage("未申请入驻信息");
            return result;
        }

        result.setCode(200);
        result.setSuccess(true);
        result.setResult(ysyOnsiteApply);
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param ysyOnsiteApply
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, YsyOnsiteApply ysyOnsiteApply) {
        return super.exportXls(request, ysyOnsiteApply, YsyOnsiteApply.class, "驻场申请");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, YsyOnsiteApply.class);
    }

}
